package com.yuanjiu.webmagic;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.downloader.AbstractDownloader;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.PlainText;
import us.codecraft.webmagic.utils.UrlUtils;

public class SeleniumDownloader extends AbstractDownloader implements Closeable{
	
	private volatile WebDriverPool webDriverPool; 

//	private Logger logger = Logger.getLogger(getClass());
//
	@SuppressWarnings("unused")
	private int sleepTime = 0;

	private int poolSize = 1;
	
//	private static final String DRIVER_PHANTOMJS = "phantomjs";
	
	private WebDriver webDriver;
	
	public SeleniumDownloader(String chromeDriverPath) {
		System.getProperties().setProperty("webdriver.chrome.driver",
				chromeDriverPath);
	}

	
	public SeleniumDownloader() {
		// System.setProperty("phantomjs.binary.path",
		// "/Users/Bingo/Downloads/phantomjs-1.9.7-macosx/bin/phantomjs");
	}
	
	public SeleniumDownloader setSleepTime(int sleepTime2) {
		this.sleepTime = sleepTime2;
		return this;
	}
	


	@SuppressWarnings("deprecation")
	@Override
	public Page download(Request request, Task task) {
		// TODO Auto-generated method stub
		
		 WebDriver driver = null;
		try {
			driver = webDriverPool.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 	driver.get(request.getUrl());
		
		 	WebDriver.Options manage = webDriver.manage();
			Site site = task.getSite(); 
			if (site.getCookies() != null) {
				for (Map.Entry<String, String> cookieEntry : site.getCookies()
						.entrySet()) {
					Cookie cookie = new Cookie(cookieEntry.getKey(),
							cookieEntry.getValue());
					manage.addCookie(cookie);
				}
			}
		 	
			
			WebElement webElement = webDriver.findElement(By.xpath("/html"));
			String content = webElement.getAttribute("outerHTML");
			Page page = new Page();
			page.setRawText(content);
			page.setHtml(new Html(UrlUtils.fixAllRelativeHrefs(content,
					request.getUrl())));
			page.setUrl(new PlainText(request.getUrl()));
			page.setRequest(request);
			
			
			webDriverPool.returnToPool(webDriver);
		
			return page;
	}

	@SuppressWarnings("unused")
	private void checkInit() {
		if (webDriverPool == null) {
			synchronized (this) {
				webDriverPool = new WebDriverPool(poolSize);
			}
		}
	}

	@Override
	public void setThread(int thread) {
		this.poolSize = thread;
	}

	@Override
	public void close() throws IOException {
		webDriverPool.closeAll();
	}

}
